package beusoft.ccjk.com.calculator.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * Created by CCJK on 2017/12/28.
 */

public class Demo {


    private static void println(Object o) {
        System.out.println(o);
    }

    private static void print(Object o) {
        System.out.print(" " + o);
    }

    private static void printArr(int arr[]) {
        print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                print(arr[i]);
            } else {
                print(arr[i] + " , ");
            }

        }
        print("]");
    }

    public static void main(String... args) {
        try {
            Socket socket = new Socket("192.168.1.144", 7979);
            if (socket.isConnected()) {
                print("已经链接");
                sendInfo(socket.getOutputStream());
                printInputStream(socket.getInputStream());
            } else print("没有链接");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void sendInfo(OutputStream outputStream) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("GET").append(" ").append("/wenda/data/categories").append(" ").append("HTTP/1.1").append("\n");
        stringBuilder.append("Host: 192.168.1.144").append("\n");
        stringBuilder.append("Connection: Keep-Alive").append("\n");
        stringBuilder.append("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)").append("\n");
        stringBuilder.append("\n");


        bufferedWriter.write(stringBuilder.toString());
    }

    private static void printInputStream(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String s = null;
        while (true) {
            s = reader.readLine();
            if (s == null || s.length() == 0) {
                break;
            }
            println(s);
        }

    }

}
